<template>
  <div>
    <el-row style="margin-top: 20px">
      <el-col :span="20" :offset="2">
<!-- 我的文章表格 -->
        <el-table
            :data="tableData"
            border
            style="width: 100%">
          <el-table-column
              prop="title"
              label="标题"
              width="180">
          </el-table-column>
          <el-table-column
              prop="content"
              label="内容"
              width="180">
            <template slot-scope="scope" >
              <el-link v-show="isLogin" @click="showArticle(scope.row)" type="primary">点击查看文章内容</el-link>
            </template>

          </el-table-column>
          <el-table-column
              prop="createTime"
              label="创建时间">
          </el-table-column>
          <el-table-column label="操作"  >
            <template slot-scope="scope">
              <el-button v-show="isLogin" type="primary" @click="editArticleContent(scope.row)" icon="el-icon-edit">编辑</el-button>&nbsp;
              <el-popconfirm
                  v-show="isLogin"
                  title="你确定删除吗？"
                  v-on:confirm="deleteArticle(scope.row.id)"
              >
                <el-button slot="reference" type="danger" icon="el-icon-delete">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

<!--  Dialog框      -->
        <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogVisible"
            :width="dialogWidth">
          <!--  预览文章  -->
          <mavon-editor
              class="md"
              v-show="dialogTitle==='预览'"
              :value="mavonDditorContent"
              :subfield="false"
              :default-open="'preview'"
              :toolbars-flag="false"
              :editable="false"
              :scroll-style="false"
              :scrollStyle="true"
              :ishljs="true"
          />
          <!--   markdown编辑  -->
          <el-form :model="ruleForm"  status-icon label-position="top" v-show="dialogTitle==='编辑'"
                   :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="发表标题:" prop="articleTitle">
              <el-col :span="10">
                <el-input type="text" v-model="ruleForm.title" placeholder="请输入标题"
                          autocomplete="off"></el-input>
              </el-col>
            </el-form-item>
            <mavon-editor

                v-model="ruleForm.content"
                ref="md"
                @imgAdd="imgAdd"
                :ishljs="true"
                style="min-height: 400px"
            />
          </el-form>
          <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary"  v-show="dialogTitle==='预览'" @click="dialogVisible = false">确 定</el-button>
          <el-button type="primary"  v-show="dialogTitle==='编辑'"
                     @click="saveEditArticle()">确 定</el-button>
      </span>
        </el-dialog>

 <!--  文章分页  -->
        <div class="block" style="display: flex;justify-content: center;margin-top: 20px">

          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[2, 3, 5, 10]"
              :page-size="pageFormData.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: "MyArticlePage",
  inject:['reload'],
  data(){
    var titleValidator = (rule,value,callback)=>{
      if (value === ''){
        callback(new Error("标题不能为空!"))
      }else{
        callback();
      }
    }
    return{
      dialogVisible: false,//dialog框的显示控制
      dialogTitle:'', //dialog的标题名
      dialogWidth:'30%',//dialog框的宽度
      mavonDditorContent:'',//预览内容
      currentPage:1,//分页的当前页
      total:0,
      pageFormData:{
        pageNum: 1,
        pageSize:2,
        uid:''
      },
      ruleForm:{ //编辑表单
        id:'',
        title:'',
        content:''
      },
      rules:{
        articleTitle:[
          {validator:titleValidator,trigger:'blur'}
        ]
      },
      tableData: [{//表格数据
        id:'',
        title:'',
        content:'',
        createTime:''
      }],
      isLogin:false,
    }
  },
  mounted() {
    this.isLogin = this.$store.getters["LoginModule/getStatus"];
    if (this.isLogin){
      this.load()
    }
  },
  methods:{
    load(){//初始加载

      //获取用户信息中的id
      this.pageFormData.uid = JSON.parse(localStorage.getItem('user')).id;
      //请求分页结果
      this.$api.page(this.pageFormData).then((res)=>{
        if (res.code === 200){
           this.total = res.data.pageList;
          this.tableData = res.data.onePageList;
          //处理后端返回的时间数据格式
          this.tableData.map((item)=>{
            item.createTime = this.timestampToDate(item.createTime)
          })
        }
      })
    },
    //点击显示对应的文章内容
    showArticle(row){
      this.dialogVisible = true;
      this.dialogTitle = '预览';
      this.dialogWidth = '30%';

      this.mavonDditorContent = row.content;
    },
    //点击编辑按钮
    editArticleContent(row){
      this.dialogVisible = true;
      this.dialogTitle = '编辑';
      this.dialogWidth = '60%';

      this.ruleForm.id = row.id;
      this.ruleForm.title = row.title;
      this.ruleForm.content = row.content;
    },
    //点击编辑中的确定按钮,保存文件
    saveEditArticle(){
      if (this.ruleForm.articleTitle === '' || this.ruleForm.mavonDditorContent===''){
        this.$message.error("请输入文章标题和文章内容!")
      }
      this.$api.updateArticle(this.ruleForm).then((res)=>{
        if (res.code === 200){
          this.$message.success("编辑成功!");
          this.reload();
        }else{
          this.$message.error("编辑失败!");
        }
      })
    },
    //删除文章
    deleteArticle(id){
      this.$api.deleteArticle(id).then((res)=>{
        this.reload();
      })
    },
    // 将图片上传到服务器，返回地址替换到md中
    imgAdd(pos, $file){
      //将图片上传到服务器
      let formdata = new FormData()
      formdata.append('file', $file)
      this.$api.upload(formdata).then(res => {
        //将返回的url替换到文本原位置
        this.$refs.md.$img2Url(pos, res.data);
      }).catch(err => {
        console.log(err)
      })
    },
    handleSizeChange(val) {
      this.pageFormData.pageSize = val;
      this.load();
    },
    handleCurrentChange(val) {
      this.pageFormData.pageNum = val;
      this.load();

    },
    //处理后端传递的时间数据
    timestampToDate(Timestamp){
        let date1 = new Date(Timestamp);
        return date1.toLocaleDateString().replace(/\//g, "-") + " " + date1.toTimeString().substr(0, 8);
    }


}
}
</script>

<style scoped>

</style>